<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="药品名称" prop="drugName">
        <el-input
          v-model="queryParams.drugName"
          placeholder="请输入药品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="兽药批号" prop="batchNumber">
        <el-input
          v-model="queryParams.batchNumber"
          placeholder="请输入兽药批号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="库存状态" prop="inventoryStatus">
        <el-select v-model="queryParams.inventoryStatus" placeholder="请选择库存状态" clearable>
          <el-option label="正常" value="正常" />
          <el-option label="临期" value="临期" />
          <el-option label="过期" value="过期" />
          <el-option label="冻结" value="冻结" />
        </el-select>
      </el-form-item>
      <el-form-item label="存储条件" prop="storageCondition">
        <el-select v-model="queryParams.storageCondition" placeholder="请选择存储条件" clearable>
          <el-option label="常温" value="常温" />
          <el-option label="冷藏" value="冷藏" />
          <el-option label="冷冻" value="冷冻" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['veterinary:inventory:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['veterinary:inventory:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['veterinary:inventory:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['veterinary:inventory:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-warning"
          size="mini"
          @click="handleWarning"
        >库存预警</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-time"
          size="mini"
          @click="handleExpiring"
        >即将过期</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="inventoryList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="库存ID" align="center" prop="inventoryId" />
      <el-table-column label="药品名称" align="center" prop="drugName" :show-overflow-tooltip="true" />
      <el-table-column label="规格" align="center" prop="drugSpecification" />
      <el-table-column label="药品厂家" align="center" prop="manufacturerName" :show-overflow-tooltip="true" />
      <el-table-column label="兽药批号" align="center" prop="batchNumber" />
      <el-table-column label="进价" align="center" prop="purchasePrice">
        <template slot-scope="scope">
          <span>¥{{ parseFloat(scope.row.purchasePrice).toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="数量" align="center" prop="quantity">
        <template slot-scope="scope">
          <span :class="scope.row.quantity <= scope.row.warningQuantity ? 'text-danger' : ''">
            {{ scope.row.quantity }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="休药期" align="center" prop="withdrawalPeriod">
        <template slot-scope="scope">
          <span>{{ scope.row.withdrawalPeriod }}天</span>
        </template>
      </el-table-column>
      <el-table-column label="有效期至" align="center" prop="expiryDate" width="180">
        <template slot-scope="scope">
          <span :class="getDaysToExpiry(scope.row.expiryDate) <= 30 ? 'text-danger' : ''">
            {{ parseTime(scope.row.expiryDate, '{y}-{m}-{d}') }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="库存状态" align="center" prop="inventoryStatus">
        <template slot-scope="scope">
          <el-tag 
            :type="getStatusType(scope.row.inventoryStatus)"
          >
            {{ scope.row.inventoryStatus }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="存储条件" align="center" prop="storageCondition">
        <template slot-scope="scope">
          <el-tag 
            :type="scope.row.storageCondition === '常温' ? 'info' : scope.row.storageCondition === '冷藏' ? 'primary' : 'warning'"
          >
            {{ scope.row.storageCondition }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['veterinary:inventory:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['veterinary:inventory:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改仓库管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="药品名称" prop="drugName">
              <el-input v-model="form.drugName" placeholder="请输入药品名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="规格" prop="drugSpecification">
              <el-input v-model="form.drugSpecification" placeholder="如：10%/100g/袋" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="药品厂家" prop="manufacturerId">
              <el-select v-model="form.manufacturerId" placeholder="请选择药品厂家" filterable>
                <el-option
                  v-for="manufacturer in manufacturerList"
                  :key="manufacturer.manufacturerId"
                  :label="manufacturer.manufacturerName"
                  :value="manufacturer.manufacturerId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="兽药批号" prop="batchNumber">
              <el-input v-model="form.batchNumber" placeholder="请输入兽药批号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="进价" prop="purchasePrice">
              <el-input-number v-model="form.purchasePrice" :precision="2" :step="0.01" :min="0" placeholder="请输入进价" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="数量" prop="quantity">
              <el-input-number v-model="form.quantity" :min="0" placeholder="请输入数量" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="休药期" prop="withdrawalPeriod">
              <el-input-number v-model="form.withdrawalPeriod" :min="0" placeholder="请输入休药期（天）" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="有效期至" prop="expiryDate">
              <el-date-picker
                v-model="form.expiryDate"
                type="date"
                placeholder="选择有效期"
                value-format="yyyy-MM-dd">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="库存状态" prop="inventoryStatus">
              <el-select v-model="form.inventoryStatus" placeholder="请选择库存状态">
                <el-option label="正常" value="正常" />
                <el-option label="临期" value="临期" />
                <el-option label="过期" value="过期" />
                <el-option label="冻结" value="冻结" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="存储条件" prop="storageCondition">
              <el-select v-model="form.storageCondition" placeholder="请选择存储条件">
                <el-option label="常温" value="常温" />
                <el-option label="冷藏" value="冷藏" />
                <el-option label="冷冻" value="冷冻" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="适用动物" prop="applicableAnimals">
              <el-input v-model="form.applicableAnimals" placeholder="请输入适用动物" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="病症类型" prop="diseaseType">
              <el-input v-model="form.diseaseType" placeholder="请输入病症类型" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="库存预警数量" prop="warningQuantity">
              <el-input-number v-model="form.warningQuantity" :min="0" placeholder="请输入预警数量" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="关键字" prop="keywords">
          <el-input v-model="form.keywords" type="textarea" placeholder="请输入关键字（含适用动物、病症类型标签）" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 库存预警对话框 -->
    <el-dialog title="库存预警" :visible.sync="warningOpen" width="1000px" append-to-body>
      <el-table :data="warningList" style="width: 100%">
        <el-table-column label="药品名称" prop="drugName" />
        <el-table-column label="规格" prop="drugSpecification" />
        <el-table-column label="当前库存" prop="quantity">
          <template slot-scope="scope">
            <span class="text-danger">{{ scope.row.quantity }}</span>
          </template>
        </el-table-column>
        <el-table-column label="预警数量" prop="warningQuantity" />
        <el-table-column label="兽药批号" prop="batchNumber" />
        <el-table-column label="有效期至" prop="expiryDate">
          <template slot-scope="scope">
            {{ parseTime(scope.row.expiryDate, '{y}-{m}-{d}') }}
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 即将过期对话框 -->
    <el-dialog title="即将过期药品" :visible.sync="expiringOpen" width="1000px" append-to-body>
      <el-table :data="expiringList" style="width: 100%">
        <el-table-column label="药品名称" prop="drugName" />
        <el-table-column label="规格" prop="drugSpecification" />
        <el-table-column label="库存数量" prop="quantity" />
        <el-table-column label="兽药批号" prop="batchNumber" />
        <el-table-column label="有效期至" prop="expiryDate">
          <template slot-scope="scope">
            <span class="text-danger">{{ parseTime(scope.row.expiryDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="剩余天数" prop="expiryDate">
          <template slot-scope="scope">
            <span class="text-danger">{{ getDaysToExpiry(scope.row.expiryDate) }}天</span>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import { listInventory, getInventory, delInventory, addInventory, updateInventory, getWarningList, getExpiringList } from "@/api/veterinary/inventory";

export default {
  name: "Inventory",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 仓库管理表格数据
      inventoryList: [],
      // 库存预警列表
      warningList: [],
      // 即将过期列表
      expiringList: [],
      // 药品厂家列表
      manufacturerList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示预警对话框
      warningOpen: false,
      // 是否显示过期对话框
      expiringOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        drugName: null,
        drugSpecification: null,
        manufacturerId: null,
        batchNumber: null,
        inventoryStatus: null,
        storageCondition: null,
        applicableAnimals: null,
        keywords: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        drugName: [
          { required: true, message: "药品名称不能为空", trigger: "blur" }
        ],
        drugSpecification: [
          { required: true, message: "规格不能为空", trigger: "blur" }
        ],
        manufacturerId: [
          { required: true, message: "药品厂家不能为空", trigger: "change" }
        ],
        batchNumber: [
          { required: true, message: "兽药批号不能为空", trigger: "blur" }
        ],
        purchasePrice: [
          { required: true, message: "进价不能为空", trigger: "blur" }
        ],
        quantity: [
          { required: true, message: "数量不能为空", trigger: "blur" }
        ],
        expiryDate: [
          { required: true, message: "有效期至不能为空", trigger: "change" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getManufacturerList();
  },
  methods: {
    /** 查询仓库管理列表 */
    getList() {
      this.loading = true;
      listInventory(this.queryParams).then(response => {
        this.inventoryList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 获取厂家列表 */
    /** 获取厂家列表 */
    getManufacturerList() {
      import("@/api/veterinary/manufacturer").then(manufacturerApi => {
        manufacturerApi.listManufacturer({}).then(response => {
          this.manufacturerList = response.rows || [];
        }).catch(() => {
          // 如果API调用失败，使用模拟数据
          this.manufacturerList = [
            { manufacturerId: 1, manufacturerName: "华畜兽药有限公司" },
            { manufacturerId: 2, manufacturerName: "康达生物制药" },
            { manufacturerId: 3, manufacturerName: "绿康动保科技" }
          ];
        });
      }).catch(() => {
        // 如果模块加载失败，使用模拟数据
        this.manufacturerList = [
          { manufacturerId: 1, manufacturerName: "华畜兽药有限公司" },
          { manufacturerId: 2, manufacturerName: "康达生物制药" },
          { manufacturerId: 3, manufacturerName: "绿康动保科技" }
        ];
      });
    },
    /** 获取库存状态标签类型 */
    getStatusType(status) {
      const statusMap = {
        '正常': 'success',
        '临期': 'warning',
        '过期': 'danger',
        '冻结': 'info'
      };
      return statusMap[status] || 'info';
    },
    /** 计算距离过期天数 */
    getDaysToExpiry(expiryDate) {
      const today = new Date();
      const expiry = new Date(expiryDate);
      const diffTime = expiry - today;
      const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
      return diffDays;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        inventoryId: null,
        drugName: null,
        drugSpecification: null,
        manufacturerId: null,
        batchNumber: null,
        purchasePrice: null,
        quantity: null,
        withdrawalPeriod: null,
        expiryDate: null,
        inventoryStatus: "正常",
        storageCondition: "常温",
        applicableAnimals: null,
        diseaseType: null,
        keywords: null,
        warningQuantity: 10
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.inventoryId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加库存信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const inventoryId = row.inventoryId || this.ids
      getInventory(inventoryId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改库存信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.inventoryId != null) {
            updateInventory(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addInventory(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const inventoryIds = row.inventoryId || this.ids;
      this.$modal.confirm('是否确认删除库存信息编号为"' + inventoryIds + '"的数据项？').then(function() {
        return delInventory(inventoryIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('veterinary/inventory/export', {
        ...this.queryParams
      }, `inventory_${new Date().getTime()}.xlsx`)
    },
    /** 库存预警按钮操作 */
    handleWarning() {
      getWarningList().then(response => {
        this.warningList = response.data;
        this.warningOpen = true;
      });
    },
    /** 即将过期按钮操作 */
    handleExpiring() {
      getExpiringList(30).then(response => {
        this.expiringList = response.data;
        this.expiringOpen = true;
      });
    }
  }
};
</script>

<style scoped>
.text-danger {
  color: #f56c6c;
  font-weight: bold;
}
</style>